import React from 'react'
import PropTypes from 'prop-types'
import * as $helpers from './helpers'

export default function Connect(props, context) {
  const {
    as: Tag,
    children,
    $query,
    ...restProps
  } = props
  const { state } = context
  for (let key in $query) {
    try {
      const value = $helpers.getValueByPath(state, key)
      restProps[$query[key]] = value
    } catch (error) {
      console.warn(error)
    }
  }
  return (
    <Tag {...restProps}>{children}</Tag>
  )
}

Connect.defaultProps = {
  as: 'div',
}

Connect.contextTypes = {
  state: PropTypes.object,
}